const app = getApp()

Page({
  data: {
    tasks: [],
    loading: true,
    pageIndex: 1,
    pageSize: 10,
    hasMore: true,
    searchValue: ''
  },

  onLoad() {
    this.loadTasks()
  },

  onPullDownRefresh() {
    this.setData({
      tasks: [],
      pageIndex: 1,
      hasMore: true
    })
    this.loadTasks()
  },

  onReachBottom() {
    if (this.data.hasMore && !this.data.loading) {
      this.loadMore()
    }
  },

  // 加载工单列表
  loadTasks() {
    this.setData({ loading: true })
    const { pageIndex, pageSize, searchValue } = this.data
    
    wx.request({
      url: `${app.globalData.baseUrl}/task/list`,
      method: 'GET',
      data: {
        pageIndex,
        pageSize,
        searchValue
      },
      header: {
        'Authorization': `Bearer ${app.globalData.token}`
      },
      success: (res) => {
        if (res.data.code === 200) {
          const { currentPageRecords, totalCount, totalPage } = res.data.data
          const hasMore = pageIndex < totalPage
          
          this.setData({
            tasks: pageIndex === 1 ? currentPageRecords : [...this.data.tasks, ...currentPageRecords],
            hasMore,
            loading: false
          })
        } else {
          wx.showToast({
            title: res.data.msg || '加载失败',
            icon: 'none'
          })
          this.setData({ loading: false })
        }
      },
      fail: () => {
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        })
        this.setData({ loading: false })
      }
    })
  },

  // 加载更多
  loadMore() {
    if (this.data.hasMore && !this.data.loading) {
      this.setData({
        pageIndex: this.data.pageIndex + 1
      })
      this.loadTasks()
    }
  },

  // 搜索输入
  onSearchInput(e) {
    this.setData({
      searchValue: e.detail.value
    })
  },

  // 搜索
  onSearch() {
    this.setData({
      tasks: [],
      pageIndex: 1,
      hasMore: true
    })
    this.loadTasks()
  },

  // 跳转到工单详情
  goToDetail(e) {
    const taskId = e.currentTarget.dataset.taskId
    wx.navigateTo({
      url: `/pages/task/task-detail?taskId=${taskId}`
    })
  }
}) 